package xidw_api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"reflect"
	"server/apps/xidw/xidw_mod"
	"server/global"
	"server/model/common/request"
	"server/model/common/response"
	"server/utils"
	"strconv"
	"strings"
)

type FileUploadAndDownloadApi struct{}
type FileUploadResponse struct {
	File xidw_mod.FileUploadAndDownload `json:"file"`
}

func (b *FileUploadAndDownloadApi) UploadFile(c *gin.Context) {
	var file xidw_mod.FileUploadAndDownload
	noSave := c.DefaultQuery("noSave", "0")
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		global.Logger.Error("接收文件失败!", zap.Error(err))
		response.FailWithMessage("接收文件失败", c)
		return
	}
	file, err = fileUploadAndDownloadService.UploadFile(header, noSave)
	fmt.Printf("upload api:%+v\n", file)
	if err != nil {
		global.Logger.Error("修改数据库链接失败!", zap.Error(err))
		response.FailWithMessage("修改数据库链接失败", c)
		return
	}
	var uploadList [][]string
	fileTypeList := strings.Split(file.Name, ".")
	if len(fileTypeList) < 1 {
		global.Logger.Error("上传文件没有文件名!")
		response.FailWithMessage("上传文件没有文件名", c)
		return
	}
	switch fileTypeList[len(fileTypeList)-1] {
	case "csv":
		uploadList = utils.ReadCsv(file.Url)
	case "xls":
		uploadList = utils.ReadXls(file.Url)
	case "xlsx":
		uploadList = utils.ReadXlsx(file.Url)
	default:
		global.Logger.Error("上传文件格式必须为csv,xls,xlsx")
		response.FailWithMessage("上传文件格式必须为csv,xls,xlsx", c)
		return
	}
	fmt.Printf("文件内容：\n%+v\n", uploadList)
	if len(uploadList) <= 2 {
		global.Logger.Error("上传文件内容至少一行")
		response.FailWithMessage("上传文件内容至少一行", c)
		return
	}
	colNameList := []string{"ColName", "ColDataType", "ColComment", "ColKey", "Unique", "NotNull", "AutoIncrement", "Remarks"}
	if !reflect.DeepEqual(uploadList[0], colNameList) {
		global.Logger.Error("上传文件title错误")
		response.FailWithMessage("上传文件title错误", c)
		return
	}
	type TmpFld struct {
		ColName       string `json:"colName"`
		ColDataType   string `json:"colDataType"`
		ColComment    string `json:"colComment"`
		ColKey        bool   `json:"colKey"`
		Unique        bool   `json:"unique"`
		NotNull       bool   `json:"notNull"`
		AutoIncrement bool   `json:"autoIncrement"`
		Remarks       string `json:"remarks"`
	}
	var fldList []TmpFld
	for _, oneRow := range uploadList[2:] {
		var t TmpFld
		t.ColName = oneRow[0]
		t.ColDataType = oneRow[1]
		t.ColComment = oneRow[2]
		t.ColKey, err = strconv.ParseBool(oneRow[3])
		if err != nil {
			global.Logger.Error("‘是否主键’需填bool值")
			response.FailWithMessage("‘是否主键’需填bool值", c)
			return
		}
		t.Unique, err = strconv.ParseBool(oneRow[4])
		if err != nil {
			global.Logger.Error("‘是否唯一’需填bool值")
			response.FailWithMessage("‘是否唯一’需填bool值", c)
			return
		}
		t.NotNull, err = strconv.ParseBool(oneRow[5])
		if err != nil {
			global.Logger.Error("‘是否必填’需填bool值")
			response.FailWithMessage("‘是否必填’需填bool值", c)
			return
		}
		t.AutoIncrement, err = strconv.ParseBool(oneRow[6])
		if err != nil {
			global.Logger.Error("‘是否自增’需填bool值")
			response.FailWithMessage("‘是否自增’需填bool值", c)
			return
		}
		t.Remarks = oneRow[7]
		fldList = append(fldList, t)
	}

	response.OkWithDetailed(gin.H{"file": file, "flds": fldList}, "上传成功", c)
}

func (b *FileUploadAndDownloadApi) EditFileName(c *gin.Context) {
	var file xidw_mod.FileUploadAndDownload
	err := c.ShouldBindJSON(&file)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = fileUploadAndDownloadService.EditFileName(file)
	if err != nil {
		global.Logger.Error("编辑失败!", zap.Error(err))
		response.FailWithMessage("编辑失败", c)
		return
	}
	response.OkWithMessage("编辑成功", c)
}

func (b *FileUploadAndDownloadApi) DeleteFile(c *gin.Context) {
	var file xidw_mod.FileUploadAndDownload
	err := c.ShouldBindJSON(&file)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := fileUploadAndDownloadService.DeleteFile(file); err != nil {
		global.Logger.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

func (b *FileUploadAndDownloadApi) GetFileList(c *gin.Context) {
	var pageInfo request.PageInfo
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := fileUploadAndDownloadService.GetFileRecordInfoList(pageInfo)
	if err != nil {
		global.Logger.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}
